import { OrderType } from '@/enums'
import {
  cancelOrder,
  deleteOrder,
  followOrUnfollow,
  getPrescriptionPic
} from '@/services/consult'
import { getMedicalOrderDetail } from '@/services/order'
import { getMobileCode } from '@/services/user'
import type { CodeType } from '@/types'
import type { ConsultOrderItem, FollowType } from '@/types/consult'
import type { OrderDetail } from '@/types/order'
import { useClipboard } from '@vueuse/core'
import {
  showFailToast,
  showImagePreview,
  showSuccessToast,
  showToast,
  type FormInstance
} from 'vant'
import type { Ref } from 'vue'
import { onMounted, onUnmounted, ref } from 'vue'

export const useOrderDetail = (id: string) => {
  const loading = ref(false)
  const order = ref<OrderDetail>()
  onMounted(async () => {
    loading.value = true
    try {
      const res = await getMedicalOrderDetail(id)
      order.value = res.data
    } finally {
      loading.value = false
    }
  })
  return { order, loading }
}

// #region 复制
const { copy: copyOfVueUse, isSupported } = useClipboard()
export const useCopy = () => {
  const copy = (text: string) => {
    // 当 localhost 或 127.0.0.1 时 不会检查权限
    // 当 https 时，会检查权限，需要用户授权
    // 如果是 http 其他的域名，是没有权限的
    if (!isSupported.value) return showToast('未授权，不支持')
    if (!text) return showToast('不能复制空文本')
    copyOfVueUse(text).then(() => {
      showToast('已复制')
    })
  }

  return { copy }
}
// #endregion

export const useDeleteOrder = (cb: () => void) => {
  // 删除订单
  const loading = ref(false)
  const deleteConsultOrder = async (item: ConsultOrderItem) => {
    try {
      loading.value = true
      await deleteOrder(item.id)
      showSuccessToast('删除成功')
      // 成功，做其他业务
      cb && cb()
    } catch (e) {
      showFailToast('删除失败')
    } finally {
      loading.value = false
    }
  }
  return { loading, deleteConsultOrder }
}

// 封装取消订单逻辑
export const useCancelOrder = () => {
  const loading = ref(false)
  const cancelConsultOrder = async (item: ConsultOrderItem) => {
    try {
      loading.value = true
      await cancelOrder(item.id)
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
      showSuccessToast('取消成功')
    } catch (error) {
      showFailToast('取消失败')
    } finally {
      loading.value = false
    }
  }
  return { loading, cancelConsultOrder }
}

// 封装查看处方逻辑
export const useShowPrescription = () => {
  const onShowPrescription = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id)
      showImagePreview([res])
    }
  }
  return { onShowPrescription }
}

// 关注操作的组合式API
const useFollow = (type: FollowType = 'doc') => {
  const loading = ref(false)

  const follow = async (item: { id: string; likeFlag: 0 | 1 }) => {
    loading.value = true
    try {
      await followOrUnfollow(item.id, type)
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
    } finally {
      loading.value = false
    }
  }

  return { loading, follow }
}

export { useFollow }

// const { loading, follow } = useFollow('doc')

/**
 * 发送短信验证码 hook 函数
 * @param mobile 手机号码
 * @param type 验证码类型
 */
export const useSendMobileCode = (mobile: Ref<string>, type: CodeType) => {
  const refForm = ref<FormInstance | null>(null)

  // 倒计时
  const time = ref(0)

  // 收到的验证码
  const code = ref('')

  // 定时器id
  let timerId = -1

  // 发送验证码
  const send = async () => {
    // 如果目前已经在倒计时中，就直接 return
    if (time.value > 0) return

    // 先验证手机号码有没有输入正确
    await refForm.value?.validate('mobile')

    // 如果能走到这里，说明验证通过
    // 发请求
    code.value = await getMobileCode(mobile.value, type)

    // 倒计时效果什么时候开启，请求发送成功
    showSuccessToast('发送成功')
    time.value = 60
    timerId = setInterval(() => {
      time.value--
      if (time.value === 0) {
        clearInterval(timerId)
      }
    }, 1000)
  }

  onUnmounted(() => {
    // 页面卸载的同时清除定时器
    clearInterval(timerId)
  })

  return { refForm, time, send, code }
}
